
import {getParam} from '../utils/Tools'
let tabID
chrome.tabs.onCreated.addListener(function(tab) {
  if(tab.pendingUrl === "https://mp.weixin.qq.com/" || tab.url === "https://mp.weixin.qq.com/"){
    console.log('打开新窗口')
  }else{
    tabID = localStorage.getItem(`sinyu_cookie_${getParam(tab.pendingUrl,'token')}`)
  }
});
window.tabID = tabID

///          拦截请求获取所有请求头
chrome.webRequest.onBeforeSendHeaders.addListener(details=>{
  details.requestHeaders.some(res=>{
    if(res.name == 'Cookie' && tabID){
      res.value = tabID
    }else if( res.name == 'Cookie' && (  details.url.includes("/useranalysis") ||  details.url.includes("/checkorgrealnamestate")||  details.url.includes("/appmsgotherinfo"))) {
      tabID = res.value
      return true;
    }
    return false;
  })
  details.requestHeaders.push({
    name: 'authorization',
    value: localStorage.getItem('authorization') || ""
  });
  return  {
    requestHeaders: details.requestHeaders
  };
},{
  urls:['*://*.kaibaizhushou.com/pluginApi/*','*://mp.weixin.qq.com/*']
},['requestHeaders','blocking',chrome.webRequest.OnBeforeSendHeadersOptions.EXTRA_HEADERS].filter(Boolean))

let email;
///    监听发送信息
chrome.runtime.onMessage.addListener((res, sender, sendResponse)=>{
  if(res.type == 'loginUser'){   ///  登录账号
    console.log('--------登录账号',res.data.email)
    const account = localStorage.getItem(`sinyu_account_${res.data.email}`) || localStorage.getItem(`sinyu_account_${res.data.userName}`)
    const token = localStorage.getItem(`sinyu_token_${res.data.email}`) || localStorage.getItem(`sinyu_token_${res.data.userName}`)
    const url = token ? `https://mp.weixin.qq.com/?token=${token}&lang=zh_CN` :`https://mp.weixin.qq.com/`
    chrome.tabs.create({
      url
    },tab=>{
      if(!account) localStorage.setItem(`sinyu_account_${res.data.email}`,JSON.stringify({"username":res.data.email}))
      email = account || JSON.stringify({"username":res.data.email})
    })
    return;
  }
  if(res.type == 'saveAccount'){   ///  保存账号
    localStorage.setItem(`sinyu_account_${res.data.username}`,JSON.stringify(res.data))
    return
  }
  if(res.type == 'saveToken'){
    localStorage.setItem(`sinyu_token_${res.data.username}`,res.data.token)
    localStorage.setItem(`sinyu_cookie_${res.data.token}`,res.data.cookie)
  }
  if(res.type == 'getAccount'){  //  获取账号
    console.log('---------------获取账号--')
    let value = JSON.parse(email)
    if(!email){
      for(let i in localStorage){
        if(i.includes('sinyu_account_')){
          value = JSON.parse(localStorage[i])
        }
      }
    }
    sendResponse(value)
  }
  if(res.type == 'postAccount'){
    console.log('---------- 上报账号 -- ')
    let cookie= ""
    chrome.cookies.getAll({
      url:"https://mp.weixin.qq.com/",
    },function(res){
      res.map(function(item){
        cookie += item.name +"="+item.value+";"
      })
    })
    setTimeout(() => {
      let data = {'cookie':cookie}
      if(email) data = {'cookie':cookie,...JSON.parse(email)}
      sendResponse(data)
    }, 1000);
    return true;
  }
  if(res.type == 'close_tab'){
    
  }
})

chrome.tabs.onRemoved.addListener(res=>{
  const token = getParam(location.search,'token')
  localStorage.removeItem(`sinyu_cookie_${token}`)
})
